package com.yc.fruitmarket.biz.impl;

import java.util.List;
import java.util.Map;

import com.yc.fruitmarket.biz.wishBiz;
import com.yc.fruitmarket.dao.DBHelper;

public class wishBizImpl implements wishBiz {
	private DBHelper db = new DBHelper();
	public int getWishCount(String uid) {
		String sql = "select count(wid) as count from wish where uid = ?";
		List<Map<String, String>> list = db.find(sql, uid);
		return Integer.parseInt(list.get(0).get("count"));
	}
	@Override
	public int addWish(String uid, String pid, String price, String num, String inventory) {
		
		String sql = "select * from wish where pid = ?";
		List<Map<String, String>> list = db.find(sql, pid);
		if(db.find(sql, pid).size() > 0) {
			//有则修改数量
			if(Integer.parseInt(list.get(0).get("wishnum")) + Integer.parseInt(num) <= Integer.parseInt(inventory)) {
				sql = "update wish set wishnum = wishnum + ? where pid = ?";
				db.doUpdate(sql,num, pid);
				return 1;
			}else {
				return 3;
			}
			
		}else {
			if(Integer.parseInt(num) <= Integer.parseInt(inventory)) {
				sql = "insert into wish values(null,?,?,?,?,1)";
				db.doUpdate(sql, uid, pid,num, price);
				return 2;
			}else {
				return 3;
			}
			
		}
	}
	@Override
	public List<Map<String, String>> getWishsByUid(String uid) {
		String sql = "select * from product,wish where product.pid = wish.pid and wish.uid = ? and wish.status = 1";
		return db.find(sql, uid);
	}
	@Override
	public int addCart(String uid, String pid, String wishnum, String wid) {
		int wishNum = Integer.parseInt(wishnum);
		String findpid = "select * from cart where pid = ? and uid = ?";
		String inventory = "select inventory from product where pid = ?";
		int countNum = Integer.parseInt(db.find(inventory, pid).get(0).get("inventory"));//商品库存数
		if(db.find(findpid, pid, uid).size() > 0) {//有修改数量
			int cartnum = Integer.parseInt(db.find(findpid, pid, uid).get(0).get("cartnum"));//购物车里的数量
			if(wishNum + cartnum <= countNum) {
				String update = "update cart set cartnum = cartnum + ? where pid = ? and uid = ?";
				int reslut = db.doUpdate(update, wishNum ,pid, uid);
				int result = deleteWish(wid);
				if(reslut > 0 && result > 0) {
					return 1;
				}
			}
			
		}else {
			if(wishNum <= countNum) {
				String insert = "insert into cart values(null,?,?,?,1)";
				int reslut = db.doUpdate(insert, uid, pid, wishNum);
				int result = deleteWish(wid);
				if(reslut > 0 && result > 0) {
					return 2;
				}
			}
		}
		return -1;
	}
	@Override
	public int deleteWish(String wid) {
		String sql = "delete from wish where wid = ?";
		return db.doUpdate(sql, wid);
	}
}
